extends Control

@onready var health_label = $TopPanel/PlayerInfo/HealthLabel
@onready var energy_label = $TopPanel/PlayerInfo/EnergyLabel
@onready var enemy_info = $BattleArea/EnemySide/EnemyPanel/EnemyContainer/EnemyInfo
@onready var enemy_health = $BattleArea/EnemySide/EnemyPanel/EnemyContainer/EnemyHealth
@onready var enemy_action = $BattleArea/EnemySide/EnemyPanel/EnemyContainer/EnemyAction
@onready var hand_container = $HandPanel/HandContainer
@onready var end_turn_button = $ActionPanel/ActionButtons/EndTurnButton
@onready var potion_button = $ActionPanel/ActionButtons/PotionButton
@onready var retreat_button = $ActionPanel/ActionButtons/RetreatButton

var game_data: GameData
var current_enemy: Enemy
var player_turn: bool = true
var card_buttons: Array[Button] = []

func _ready():
	game_data = GameData.get_instance()
	
	# 连接按钮信号
	end_turn_button.pressed.connect(_on_end_turn)
	potion_button.pressed.connect(_on_use_potion)
	retreat_button.pressed.connect(_on_retreat)
	
	# 初始化战斗
	_initialize_battle()

func _initialize_battle():
	print("初始化战斗")
	# 获取当前敌人
	if game_data.current_enemies.size() > 0:
		current_enemy = game_data.current_enemies[0]
		print("敌人: ", current_enemy.name)
	
	# 抽初始手牌
	print("抽初始手牌...")
	game_data.draw_cards_to_hand()
	
	# 更新UI
	_update_ui()
	_update_hand()
	print("战斗初始化完成")

func _update_ui():
	# 更新玩家信息
	health_label.text = "生命值: " + str(game_data.player_health) + "/" + str(game_data.player_max_health)
	energy_label.text = "能量: " + str(game_data.player_energy) + "/" + str(game_data.player_max_energy)
	
	# 更新敌人信息
	if current_enemy:
		enemy_info.text = current_enemy.name + " (" + current_enemy.exam_type + ")"
		enemy_health.text = "生命值: " + str(current_enemy.health) + "/" + str(current_enemy.max_health)
		enemy_action.text = "下回合行动: " + current_enemy.get_action()
		
		# 如果是精英或Boss，显示特殊标识
		if current_enemy.is_elite:
			enemy_info.text += " [精英]"
		if current_enemy.is_boss:
			enemy_info.text += " [Boss]"

func _update_hand():
	# 清除现有手牌按钮
	for button in card_buttons:
		button.queue_free()
	card_buttons.clear()
	
	# 创建手牌按钮
	for i in range(game_data.hand.size()):
		var card = game_data.hand[i]
		var button = Button.new()
		button.text = card.name + "\n费用:" + str(card.cost)
		button.custom_minimum_size = Vector2(120, 80)
		
		# 如果能量不足，禁用按钮
		if card.cost > game_data.player_energy:
			button.disabled = true
			button.modulate = Color.GRAY
		
		# 连接点击信号
		button.pressed.connect(_on_card_played.bind(card, button))
		
		hand_container.add_child(button)
		card_buttons.append(button)

func _on_card_played(card: Card, button: Button):
	if not player_turn or card.cost > game_data.player_energy:
		return
	
	# 使用卡牌
	if game_data.use_card(card):
		# 执行卡牌效果
		card.on_play()
		
		# 更新UI
		_update_ui()
		_update_hand()
		
		# 检查战斗是否结束
		_check_battle_end()

func _on_end_turn():
	if not player_turn:
		return
	
	player_turn = false
	
	# 敌人回合
	await _enemy_turn()
	
	# 回合结束处理
	_on_turn_end()
	
	# 开始新回合
	_start_new_turn()

func _enemy_turn():
	# 等待一秒显示敌人行动
	await get_tree().create_timer(1.0).timeout
	
	if current_enemy and current_enemy.is_alive():
		# 敌人执行行动
		current_enemy.execute_action()
		
		# 更新UI
		_update_ui()
		
		# 检查战斗是否结束
		_check_battle_end()

func _on_turn_end():
	print("回合结束")
	# 回合结束时的遗物效果
	for relic in game_data.relics:
		relic.on_turn_end()
	
	# 弃掉所有手牌
	print("弃掉手牌，当前手牌数量: ", game_data.hand.size())
	for card in game_data.hand:
		game_data.discard_pile.append(card)
	game_data.hand.clear()
	print("手牌已清空，弃牌堆数量: ", game_data.discard_pile.size())

func _start_new_turn():
	print("开始新回合")
	player_turn = true
	
	# 恢复能量
	game_data.player_energy = game_data.player_max_energy
	print("恢复能量到: ", game_data.player_energy)
	
	# 回合开始时的遗物效果
	for relic in game_data.relics:
		relic.on_turn_start()
	
	# 抽牌
	print("准备抽牌...")
	game_data.draw_cards_to_hand()
	
	# 更新UI
	_update_ui()
	_update_hand()
	print("新回合UI更新完成")

func _check_battle_end():
	# 检查玩家是否死亡
	if game_data.player_health <= 0:
		_show_game_over()
		return
	
	# 检查敌人是否全部死亡
	var all_enemies_dead = true
	for enemy in game_data.current_enemies:
		if enemy.is_alive():
			all_enemies_dead = false
			break
	
	if all_enemies_dead:
		_show_victory()

func _show_victory():
	var dialog = AcceptDialog.new()
	dialog.title = "胜利！"
	dialog.dialog_text = "你成功通过了考试！"
	dialog.add_button("继续", true)
	add_child(dialog)
	dialog.popup_centered()
	
	dialog.confirmed.connect(_on_battle_end)

func _show_game_over():
	var dialog = AcceptDialog.new()
	dialog.title = "失败"
	dialog.dialog_text = "考试失败了，游戏结束。"
	dialog.add_button("返回主菜单", true)
	add_child(dialog)
	dialog.popup_centered()
	
	dialog.confirmed.connect(_on_return_to_menu)

func _on_battle_end():
	# 战斗结束，返回地图
	game_data.in_battle = false
	game_data.current_enemies.clear()
	
	# 进入下一层
	game_data.next_floor()
	
	# 返回地图场景
	get_tree().change_scene_to_file("res://scenes/MapView.tscn")

func _on_return_to_menu():
	# 返回主菜单
	get_tree().change_scene_to_file("res://scenes/MainMenu.tscn")

func _on_use_potion():
	# 显示药水选择界面
	if game_data.potions.size() == 0:
		var dialog = AcceptDialog.new()
		dialog.title = "提示"
		dialog.dialog_text = "你没有药水可以使用。"
		dialog.add_button("确定", true)
		add_child(dialog)
		dialog.popup_centered()
		dialog.confirmed.connect(func(): dialog.queue_free())
		return
	
	# 创建药水选择对话框
	var dialog = AcceptDialog.new()
	dialog.title = "选择药水"
	var potion_list = "选择要使用的药水：\n\n"
	for i in range(game_data.potions.size()):
		var potion = game_data.potions[i]
		potion_list += str(i + 1) + ". " + potion.name + ": " + potion.description + "\n"
	dialog.dialog_text = potion_list
	dialog.add_button("取消", false)
	add_child(dialog)
	dialog.popup_centered()
	
	# 这里可以添加更复杂的药水选择逻辑

func _on_retreat():
	# 撤退确认
	var dialog = ConfirmationDialog.new()
	dialog.title = "确认撤退"
	dialog.dialog_text = "确定要撤退吗？这将结束当前战斗。"
	add_child(dialog)
	dialog.popup_centered()
	
	dialog.confirmed.connect(_on_return_to_menu)
	dialog.canceled.connect(func(): dialog.queue_free())
